import React, { useState, useEffect, useMemo } from 'react';
import { Card, Slider, Switch, InputNumber, Row, Col, Typography, Space, Divider, ConfigProvider, ColorPicker, Input } from 'antd';
import { BoldOutlined, ItalicOutlined, UnderlineOutlined } from '@ant-design/icons';
import { theme } from 'antd';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { useSegmentForm, useDebouncedSave } from './hooks';
import { TextStyle } from './types';

const { Title, Text } = Typography;

// 字体样式接口定义 - 使用统一的 TextStyle 类型
export type FontStyle = TextStyle;

interface FontStyleSettingsProps {
    disabled?: boolean;
    // 用于从 Redux 获取片段数据
    trackId?: string;
    segmentId?: string;
    // 用于防抖保存的参数
    draftId?: string;
}

// 暗黑主题配置
const darkTheme = {
    algorithm: theme.darkAlgorithm,
    token: {
        colorPrimary: '#715bb8',
        colorBgContainer: '#2a2a2a',
        colorBgElevated: '#2a2a2a',
        colorText: '#ffffff',
        colorTextSecondary: 'rgba(255, 255, 255, 0.7)',
        colorBorder: '#434343',
        colorBorderSecondary: '#434343',
        borderRadius: 6,
        colorFillSecondary: '#434343',
    },
    components: {
        Card: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextHeading: '#ffffff',
        },
        Slider: {
            trackBg: '#434343',
            trackHoverBg: '#434343',
            handleColor: '#715bb8',
            handleActiveColor: '#715bb8',
            railBg: '#434343',
            railHoverBg: '#434343',
        },
        InputNumber: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextPlaceholder: 'rgba(255, 255, 255, 0.5)',
            colorPrimaryHover: '#715bb8',
            colorPrimary: '#715bb8',
        },
        Switch: {
            colorPrimary: '#715bb8',
            colorPrimaryHover: '#715bb8',
        },
        Divider: {
            colorSplit: '#434343',
        },
        Button: {
            colorBgContainer: 'transparent',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextDisabled: 'rgba(255, 255, 255, 0.3)',
            colorBgTextHover: 'rgba(113, 91, 184, 0.1)',
            colorBorderHover: '#715bb8',
        },
        Select: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextPlaceholder: 'rgba(255, 255, 255, 0.5)',
            colorPrimaryHover: '#715bb8',
            colorPrimary: '#715bb8',
        },
        ColorPicker: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
        },
    },
};

const FontStyleSettings: React.FC<FontStyleSettingsProps> = ({ disabled = false, trackId, segmentId, draftId }) => {
    // 使用新的 store hook
    const { setCurrentSegmentInfo, updateSegmentConfig } = useSegmentForm();
    const debouncedSave = useDebouncedSave(800);
    
    // 从 Redux 获取基础数据
    const scriptData = useSelector((state: RootState) => state.drafts.scriptData);

    // 使用 useMemo 优化片段数据获取
    const segment = useMemo(() => {
        if (!trackId || !segmentId || !scriptData?.tracks) return null;

        const track = scriptData.tracks.find((track: any) => track.id === trackId);
        if (!track || !track.segments) return null;

        return track.segments.find((segment: any) => segment.id === segmentId) || null;
    }, [trackId, segmentId, scriptData?.tracks]);

    // 使用 useMemo 优化轨道数据获取
    const currentTrack = useMemo(() => {
        if (!scriptData?.tracks) return null;
        return scriptData.tracks.find((track: any) => track.id === trackId) || null;
    }, [trackId, scriptData?.tracks]);

    // 使用 useMemo 优化文本素材数据获取
    const textMaterial = useMemo(() => {
        if (!segment?.material_id || !scriptData?.materials?.texts) return null;

        const textMaterial = scriptData.materials.texts.find((text: any) => text.id === segment.material_id);
        if (!textMaterial || !textMaterial.content) return null;

        try {
            const contentData = JSON.parse(textMaterial.content);
            return {
                ...textMaterial,
                parsedContent: contentData,
            };
        } catch (error) {
            console.error('解析文本素材内容失败:', error);
            return null;
        }
    }, [segment?.material_id, scriptData?.materials?.texts]);


    // 默认的字体样式
    const defaultStyles: FontStyle[] = [
        {
            fill: {
                alpha: 1.0,
                content: {
                    render_type: 'solid',
                    solid: {
                        alpha: 1.0,
                        color: [1.0, 1.0, 1.0], // 白色
                    },
                },
            },
            range: [0, 11],
            size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            strokes: [
                {
                    width: 0,
                    content: {
                        solid: {
                            alpha: 1.0,
                            color: [1.0, 1.0, 1.0] as [number, number, number], // 白色描边
                        },
                    },
                },
            ],
        },
    ];

    // 从文本素材数据中获取 styles，如果没有则使用默认值
    const getInitialStyles = () => {
        let styles = defaultStyles;
        
        if (textMaterial?.parsedContent?.styles) {
            styles = textMaterial.parsedContent.styles;
        } else if (segment?.styles) {
            styles = segment.styles;
        }
        
        // 确保每个样式都有一个描边配置
        return styles.map(style => ({
            ...style,
            strokes: style.strokes && style.strokes.length > 0 
                ? [style.strokes[0]] // 只保留第一个描边
                : [{
                    width: 0,
                    content: {
                        solid: {
                            alpha: 1.0,
                            color: [1.0, 1.0, 1.0] as [number, number, number], // 白色描边
                        },
                    },
                }]
        }));
    };

    // 从文本素材数据中获取内容，如果没有则使用默认值
    const getInitialContent = () => {
        if (textMaterial?.parsedContent?.text) {
            return textMaterial.parsedContent.text;
        }
        return '';
    };

    const [currentStyles, setCurrentStyles] = useState<FontStyle[]>(defaultStyles);
    const [currentContent, setCurrentContent] = useState<string>('');
    const [isInitialized, setIsInitialized] = useState(false);

    // 设置当前片段信息到 store
    useEffect(() => {
        if (trackId && segmentId && draftId && segment) {
            setCurrentSegmentInfo({
                draftId,
                trackId,
                segmentId,
                type: currentTrack?.type as any,
                materialId: segment.material_id,
                start: segment.target_timerange?.start || 0,
                duration: segment.target_timerange?.duration || 0,
            });
        }
    }, [trackId, segmentId, draftId, segment, currentTrack, setCurrentSegmentInfo]);

    // 只在初始加载时从 Redux 获取数据，避免后续被重置
    useEffect(() => {
        if (!isInitialized) {
            const initialStyles = getInitialStyles();
            const initialContent = getInitialContent();
            setCurrentStyles(initialStyles);
            setCurrentContent(initialContent);
            setIsInitialized(true);
        }
    }, [textMaterial?.parsedContent?.styles, textMaterial?.parsedContent?.text, segment?.styles, isInitialized]);

    // 当选择不同片段时，重置初始化状态
    useEffect(() => {
        setIsInitialized(false);
    }, [trackId, segmentId]);


    // 更新样式
    const updateStyles = (newStyles: FontStyle[]) => {
        setCurrentStyles(newStyles);
        // 更新到 store
        updateSegmentConfig({ styles: newStyles });
        // 触发防抖保存
        debouncedSave({ styles: newStyles });
    };

    // 更新内容
    const updateContent = (newContent: string) => {
        setCurrentContent(newContent);
        // 更新到 store
        updateSegmentConfig({ text: newContent });
        // 触发防抖保存
        debouncedSave({ text: newContent });
    };

    // 更新特定样式
    const updateStyle = (index: number, updates: Partial<FontStyle>) => {
        const newStyles = [...currentStyles];
        newStyles[index] = { ...newStyles[index], ...updates };
        updateStyles(newStyles);
    };

    // 处理字体大小变化
    const handleSizeChange = (index: number, value: number) => {
        updateStyle(index, { size: value });
    };

    // 处理字体粗细变化
    const handleBoldChange = (index: number, checked: boolean) => {
        updateStyle(index, { bold: checked });
    };

    // 处理斜体变化
    const handleItalicChange = (index: number, checked: boolean) => {
        updateStyle(index, { italic: checked });
    };

    // 处理下划线变化
    const handleUnderlineChange = (index: number, checked: boolean) => {
        updateStyle(index, { underline: checked });
    };

    // 处理颜色变化
    const handleColorChange = (index: number, color: string) => {
        const rgb = hexToRgb(color);
        if (rgb) {
            updateStyle(index, {
                fill: {
                    ...currentStyles[index].fill,
                    content: {
                        ...currentStyles[index].fill.content,
                        solid: {
                            ...currentStyles[index].fill.content.solid,
                            color: [rgb.r / 255, rgb.g / 255, rgb.b / 255],
                        },
                    },
                },
            });
        }
    };

    // 处理透明度变化
    const handleAlphaChange = (index: number, value: number) => {
        updateStyle(index, {
            fill: {
                ...currentStyles[index].fill,
                alpha: value / 100,
            },
        });
    };

    // 处理描边宽度变化
    const handleStrokeWidthChange = (index: number, value: number) => {
        const newStyles = [...currentStyles];
        if (newStyles[index].strokes[0]) {
            newStyles[index] = {
                ...newStyles[index],
                strokes: [{
                    ...newStyles[index].strokes[0],
                    width: value
                }]
            };
            updateStyles(newStyles);
        }
    };

    // 处理描边颜色变化
    const handleStrokeColorChange = (index: number, color: string) => {
        const rgb = hexToRgb(color);
        if (rgb) {
            const newStyles = [...currentStyles];
            if (newStyles[index].strokes[0]) {
                newStyles[index] = {
                    ...newStyles[index],
                    strokes: [{
                        ...newStyles[index].strokes[0],
                        content: {
                            solid: {
                                ...newStyles[index].strokes[0].content.solid,
                                color: [rgb.r / 255, rgb.g / 255, rgb.b / 255]
                            }
                        }
                    }]
                };
                updateStyles(newStyles);
            }
        }
    };

    // 十六进制颜色转RGB
    const hexToRgb = (hex: string) => {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result
            ? {
                  r: parseInt(result[1], 16),
                  g: parseInt(result[2], 16),
                  b: parseInt(result[3], 16),
              }
            : null;
    };

    // RGB转十六进制
    const rgbToHex = (r: number, g: number, b: number) => {
        const toHex = (n: number) => {
            const hex = Math.round(n * 255).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        };
        return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
    };

    return (
        <ConfigProvider theme={darkTheme}>
            <div style={{ width: '100%' }}>
                <Card size="small" title="字体样式设置">
                    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                        {/* 文字内容输入 */}
                        <div style={{ marginBottom: '12px' }}>
                            <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '6px' }}>文字内容</Text>
                            <Input.TextArea
                                value={currentContent}
                                onChange={(e) => updateContent(e.target.value)}
                                placeholder="请输入文字内容"
                                disabled={disabled}
                                rows={3}
                                style={{
                                    backgroundColor: '#2a2a2a',
                                    borderColor: '#434343',
                                    color: '#ffffff',
                                }}
                            />
                        </div>

                        <Divider style={{ backgroundColor: '#434343', margin: '12px 0' }} />

                        {currentStyles.map((style, index) => (
                            <div key={index}>
                                <Title level={5} style={{ color: '#ffffff', marginBottom: '6px', fontSize: '13px' }}>
                                    样式 {index + 1}
                                </Title>

                                {/* 字体大小 */}
                                <div style={{ marginBottom: '12px' }}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '6px' }}>字体大小</Text>
                                    <Row align="middle" gutter={8}>
                                        <Col span={16}>
                                            <Slider min={8} max={72} value={style.size} onChange={(value) => handleSizeChange(index, value)} disabled={disabled} />
                                        </Col>
                                        <Col span={8}>
                                            <InputNumber
                                                min={8}
                                                max={72}
                                                value={style.size}
                                                onChange={(value) => handleSizeChange(index, typeof value === 'number' ? value : 12)}
                                                disabled={disabled}
                                                size="small"
                                                style={{ width: '100%' }}
                                                addonAfter="px"
                                            />
                                        </Col>
                                    </Row>
                                </div>

                                <Divider style={{ backgroundColor: '#434343', margin: '12px 0' }} />

                                {/* 字体样式 */}
                                <div style={{ marginBottom: '12px' }}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '6px' }}>字体样式</Text>
                                    <Row gutter={16}>
                                        <Col span={8}>
                                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                <Space>
                                                    <BoldOutlined style={{ color: '#ffffff' }} />
                                                    <Text style={{ color: '#ffffff', fontSize: '12px' }}>粗体</Text>
                                                </Space>
                                                <Switch checked={style.bold} onChange={(checked) => handleBoldChange(index, checked)} disabled={disabled} size="small" />
                                            </div>
                                        </Col>
                                        <Col span={8}>
                                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                <Space>
                                                    <ItalicOutlined style={{ color: '#ffffff' }} />
                                                    <Text style={{ color: '#ffffff', fontSize: '12px' }}>斜体</Text>
                                                </Space>
                                                <Switch checked={style.italic} onChange={(checked) => handleItalicChange(index, checked)} disabled={disabled} size="small" />
                                            </div>
                                        </Col>
                                        <Col span={8}>
                                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                <Space>
                                                    <UnderlineOutlined style={{ color: '#ffffff' }} />
                                                    <Text style={{ color: '#ffffff', fontSize: '12px' }}>下划线</Text>
                                                </Space>
                                                <Switch checked={style.underline} onChange={(checked) => handleUnderlineChange(index, checked)} disabled={disabled} size="small" />
                                            </div>
                                        </Col>
                                    </Row>
                                </div>

                                <Divider style={{ backgroundColor: '#434343', margin: '12px 0' }} />

                                {/* 字体颜色 */}
                                <div style={{ marginBottom: '12px' }}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '6px' }}>字体颜色</Text>
                                    <Row align="middle" gutter={12}>
                                        <Col span={24}>
                                            <ColorPicker
                                                value={rgbToHex(style.fill.content.solid.color[0], style.fill.content.solid.color[1], style.fill.content.solid.color[2])}
                                                onChange={(color) => handleColorChange(index, color.toHexString())}
                                                disabled={disabled}
                                                size="small"
                                                style={{ width: '100%' }}
                                                format="hex"
                                                showText
                                            />
                                        </Col>
                                    </Row>
                                    <div style={{ marginTop: '8px' }}>
                                        <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '4px' }}>透明度</Text>
                                        <Slider min={0} max={100} value={Math.round(style.fill.alpha * 100)} onChange={(value) => handleAlphaChange(index, value)} disabled={disabled} />
                                        <div style={{ textAlign: 'center', marginTop: '4px' }}>
                                            <Text style={{ color: '#ffffff', fontSize: '12px' }}>{Math.round(style.fill.alpha * 100)}%</Text>
                                        </div>
                                    </div>
                                </div>

                                <Divider style={{ backgroundColor: '#434343', margin: '12px 0' }} />

                                {/* 描边设置 */}
                                <div style={{ marginBottom: '12px' }}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px', display: 'block', marginBottom: '6px' }}>描边设置</Text>
                                    {style.strokes.length > 0 && (
                                        <div style={{ padding: '6px', backgroundColor: '#1a1a1a', borderRadius: '4px' }}>
                                            <Row align="middle" gutter={8}>
                                                <Col span={12}>
                                                    <Text style={{ color: '#ffffff', fontSize: '11px', display: 'block', marginBottom: '4px' }}>宽度</Text>
                                                    <InputNumber
                                                        min={0}
                                                        max={10}
                                                        step={0.1}
                                                        value={style.strokes[0].width}
                                                        onChange={(value) => handleStrokeWidthChange(index, typeof value === 'number' ? value : 0)}
                                                        disabled={disabled}
                                                        size="small"
                                                        style={{ width: '100%' }}
                                                    />
                                                </Col>
                                                <Col span={12}>
                                                    <Text style={{ color: '#ffffff', fontSize: '11px', display: 'block', marginBottom: '4px' }}>颜色</Text>
                                                    <ColorPicker
                                                        value={rgbToHex(style.strokes[0].content.solid.color[0], style.strokes[0].content.solid.color[1], style.strokes[0].content.solid.color[2])}
                                                        onChange={(color) => handleStrokeColorChange(index, color.toHexString())}
                                                        disabled={disabled}
                                                        size="small"
                                                        style={{ width: '100%' }}
                                                        format="hex"
                                                        showText
                                                    />
                                                </Col>
                                            </Row>
                                        </div>
                                    )}
                                </div>

                                {index < currentStyles.length - 1 && <Divider style={{ backgroundColor: '#434343', margin: '16px 0' }} />}
                            </div>
                        ))}
                    </Space>
                </Card>
            </div>
        </ConfigProvider>
    );
};

export default FontStyleSettings;
